package com.xjy.headfirst.观察者模式;

import lombok.Data;
import org.apache.commons.collections4.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 辛纪元
 */
@Data
public class WeacherData implements Subject{

    private List<Observer> list;

    private String name;

    private int age;

    public WeacherData (){
        list = new ArrayList<>();
    }

    @Override
    public void registerObserver(Observer observer) {
        System.out.println("我被注册进观察者了");
        list.add(observer);
    }

    @Override
    public void deleteObserver(Observer observer) {
        System.out.println("观察者中删除了我");
        int i = list.indexOf(observer);
        if (i>0){
            list.remove(i);
        }
    }

    @Override
    public void nofityObservers() {
        System.out.println("观察者们醒醒了,name="+name+",age:"+age);
        if (CollectionUtils.isNotEmpty(list)){
            for (Observer observer : list) {
                observer.update(name,age);
            }
        }
    }

    public void setMeasurements(String name,int age){
        this.name = name;
        this.age = age;
        measurementsChanged();
    }

    public void measurementsChanged(){
        nofityObservers();
    }

}
